import React, { Component } from 'react'
import Dimensions from 'react-dimensions'
import { fetchData } from '../../../components/AjaxConsumer'
import SelectUrl from '../../../components/SelectUrl'
import ListModelDetail from './SearchModel'
import moment from 'moment'
import styles from './index_ad.scss'
import { Form, Input, Tooltip, Icon, Row, Col, Select, Checkbox, Button, message, Modal, Radio, DatePicker } from 'antd';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const confirm = Modal.confirm;


// 主要表单组件
class SelfForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            url: this.props.url,
            getData: this.props.getData ? this.props.getData : {},
            contractUrl: '/base/data/contract/get',
            supplierUrl: '/base/supplier/get',
            modelTypeUrl: '/base/dic/get/model_type_p',
            disabled: false,
            formData: {
                contractNo: '',
                reason: '',
                purchaseNo: '',
                materialCode: '',
                materialDesc: '',
                productType: '',
            }
        };
        this.uuid = this.props.getData ? this.props.getData.data.length : 0;
        this.dbOutCode = this.props.dbOutCode
    }

    componentDidMount() {
        if (this.state.getData && this.state.getData != {}) {
            console.log('-------componentDidMount----init----');
            let length = this.props.getData ? this.props.getData.data.length : 0;
            const data = this.state.getData.data;
            console.log(data)
            for (let i = 0; i < length; i++) {
                if (i == 0) {
                    this.state.formData.contractNo = data[0].contractNo;
                    this.state.formData.reason = data[0].reason;
                    this.state.formData.purchaseNo = data[0].purchaseNo;
                }

                let model = 'names1_' + i;
                let modelDesc = 'names2_' + i;
                let modelType = 'names3_' + i;
                let requireAmount = 'names4_' + i;
                this.props.form.setFieldsValue({ [model]: data[i].model });
                this.props.form.setFieldsValue({ [modelDesc]: data[i].modelDesc })
                this.props.form.setFieldsValue({ [modelType]: data[i].modelType })
                this.props.form.setFieldsValue({ [requireAmount]: data[i].requireAmount })
            }
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        let dbOutCode = this.dbOutCode;
        this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
            if (!err) {
                this.setState({ loading: true });
                console.log('fieldsValue=== ', fieldsValue);
                ///alert(fieldsValue.datePicker);

                //发送ajax 控制请求数据规则，无值的设为空
                for (let item in fieldsValue) {
                    if (!fieldsValue[item]) {
                        fieldsValue[item] = ''
                    }
                }

                // 打印表单提交的值
                let arrfvList = new Array;

                let arrfvCommon = {
                    "contractNo": fieldsValue.contractNo
                }

                let chk = 0;

                const { form } = this.props;

                const keys = form.getFieldValue('keys');
                keys.map((k, index) => {
                    if (fieldsValue[`names1_${k}`] != null && fieldsValue[`names1_${k}`] != '') {
                        let afv = {
                            "model": form.getFieldValue(`names1_${k}`),
                            "modelDesc": form.getFieldValue(`names2_${k}`),
                            "userDefined1": form.getFieldValue(`names5_${k}`),
                            "modelType": form.getFieldValue(`names3_${k}`),
                            "amount": form.getFieldValue(`names4_${k}`)
                        }
                        let itemfv = Object.assign(afv, arrfvCommon);
                        arrfvList.push(itemfv);
                        chk = 1;
                    }
                });

                console.log('arrfvList=== ', arrfvList);

                if (chk == 0) {
                    Modal.warning({
                        title: '提示',
                        content: '请添加成品型号和数量！',
                    });
                    this.setState({ loading: false });
                    return;
                }

                this.setState({ loading: true });

                //在这里可以改造传给服务器的   values
                let url = '';
                url = this.state.url;
                console.log('this.state.url=== ', this.state.url);

                const options = {
                    //服务器的url
                    url: url,
                    type: 'post',
                    condition: JSON.stringify(arrfvList),
                    contentType: 'application/json; charset=utf-8'
                };
                fetchData(this, options, (res) => {
                    //回调函数
                    if (res.code == 1) {
                        console.log("刷新List列表")
                        this.props.refreshHandle();
                        this.props.onCancel();
                        this.setState({
                            loading: false,
                            visible: false,
                            disabled: false
                        });
                        message.success('操作成功');
                        this.props.form.resetFields();
                        this.uuid = 0
                        this.props.form.setFieldsValue(
                            {
                                keys: []
                            }
                        );
                    }
                }, (res) => {
                    if (res.code != 1) {
                        this.setState({ loading: false })
                    }
                })
            }
        });
    };

    onCancel = () => {
        this.props.form.resetFields();
        // console.log("'uid",this.uuid)
        this.uuid = 0
        this.props.form.setFieldsValue(
            {
                keys: []
            }
        );
        this.props.onCancel();
        this.setState({
            disabled: false,
        })
    };

    popClick = (value) => {
        const { form } = this.props;
        const contractNo = form.getFieldValue('contractNo');
        if (contractNo == null) {

            Modal.warning({
                title: '提示',
                content: '请选择合同号！',
            });
            return;
        }
        this.refs.listModelDetail.showModal(value, contractNo);
        this.refs.listModelDetail.refreshHandle();
        // this.props.refreshHandle();
    };

    // 成品型号选择弹出模态框的统一回调函数
    getListModelDetailData = (resultData) => {

        console.log("getListModelDetailData");
        let k = resultData.k;
        let model = `names1_${k}`;
        let modelDesc = `names2_${k}`;
        let unit = `names5_${k}`;
        let modelType = `names3_${k}`;

        this.props.form.setFieldsValue(
            {
                [model]: resultData.model,
                [modelDesc]: resultData.modelDesc,
                [unit]: resultData.unit,
                [modelType]: resultData.modelType
            }
        );
    }

    //减少
    remove = (k) => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        // We need at least one passenger
        if (keys.length === 1) {
            return;
        }

        // can use data-binding to set
        form.setFieldsValue({
            keys: keys.filter(key => key !== k),
        });
    };

    //增加
    add = () => {
        const contractNo = this.props.form.getFieldValue('contractNo');
        if (contractNo == '') {
            Modal.warning({
                title: '提示',
                content: '请选择合同号！',
            });
            return;
        }

        this.setState({
            disabled: true
        });
        this.uuid++;
        console.log("this.uuid" + this.uuid);
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        const nextKeys = keys.concat(this.uuid);
        form.setFieldsValue({
            keys: nextKeys,
        });
    };

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const data = this.state.getData.data;
        const colNumber = 8;//一行2个
        const itemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 10 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };
        const formItemLayoutWithOutLabel = {
            wrapperCol: {
                xs: { span: 24, offset: 0 },
                sm: { span: 20, offset: 4 },
            },
        };
        let tempArr = [];
        for (let i = 0; i < this.uuid; i++) {
            tempArr.push(i)
        }
        getFieldDecorator('keys', { initialValue: tempArr });
        const keys = getFieldValue('keys');
        let userDefined3value = getFieldValue("userDefined3")
        const formItems = keys.map((k, index) => {
            return (
                <div className={styles.formItemRow}>
                    <Row key={k}>
                        <Col span={6}>
                            <FormItem {...itemLayout} label='型号' >
                                {getFieldDecorator(`names1_${k}`, {
                                    initialValue: this.state.formData.model,
                                    rules: [{
                                        required: true,
                                        whitespace: true,
                                        message: "请填写",
                                    }],
                                })(<Input disabled id='names1_${k}' />)}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem {...itemLayout} label='型号描述' >
                                {getFieldDecorator(`names2_${k}`, {
                                    initialValue: this.state.formData.modelDesc,
                                    rules: [{
                                    }],
                                })(<Input disabled id='names2_${k}' />)}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem {...itemLayout} label='型号类型'>
                                {getFieldDecorator(`names3_${k}`, {
                                    initialValue: this.state.formData.modelType,
                                    rules: [{
                                        required: true,
                                        whitespace: true,
                                        message: "请填写",
                                    }],
                                })(
                                    <SelectUrl id='names3_${k}' isDisable="true" url={this.state.modelTypeUrl} type="get" dicCode="dicCode" dicName="dicName" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={1} >
                            <Icon
                                className="dynamic-delete-button"
                                type="search"
                                onClick={() => this.popClick(k)}
                            />
                        </Col>
                        <Col span={6}>
                            <FormItem  {...itemLayout} label='数量(个数)'>
                                {getFieldDecorator(`names4_${k}`, {
                                    initialValue: '',// data.arr[index]?String(data.arr[index].names2):'',
                                    // validateTrigger: ['onChange', 'onBlur'],
                                    rules: [{
                                        required: true,
                                        whitespace: true,
                                        message: "请填写数量",
                                    }],
                                })(
                                    <Input placeholder="请填写" style={{ width: '60px', marginRight: 3 }} />
                                )}
                                {keys[keys.length - 1] == k ? (
                                    <Icon
                                        className="dynamic-delete-button"
                                        type="minus-circle-o"
                                        disabled={keys.length === 1}
                                        onClick={() => this.remove(k)}
                                    />) : null}
                            </FormItem>
                        </Col>
                        <Col span={0}>
                            <FormItem {...itemLayout} label='单位' >
                                {getFieldDecorator(`names5_${k}`, {
                                    initialValue: this.state.formData.unit,
                                    rules: [{
                                    }],
                                })(<Input disabled id='names5_${k}' />)}
                            </FormItem>
                        </Col>
                    </Row>
                </div>
            );
        });
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 }
            }
        };
        return (
            <Form
                //onSubmit={this.handleSubmit}
                style={{
                    backgroundColor: '#fff',
                    paddingTop: '20px',
                    paddingBottom: '20px'
                }}>
                <div style={{ width: '820px', height: 'auto', margin: '0 auto' }}>
                    <Row>
                        <Col span={colNumber}>
                            <FormItem {...formItemLayout} label="合同编号">
                                {getFieldDecorator('contractNo', {
                                    initialValue: this.state.formData.contractNo ? this.state.formData.contractNo : '',
                                    rules: [
                                        {
                                            required: true, whitespace: true, message: '请输入合同编号'
                                        }, {
                                            max: 100, message: '输入内容应少于100个字符'
                                        }
                                    ]
                                })(
                                    <SelectUrl url={this.state.contractUrl} type="get" dicCode="contractNo" dicName="contractNo" />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={10} style={{ height: '33px' }}>
                            <div style={{ fontSize: '14px', fontWeight: 'bold' }}>
                                登记物料
                            </div>
                        </Col>
                        <Col span={2} style={{ height: '33px', textAlign: "right", paddingRight: '30px' }}>
                            <FormItem className={styles.addFormItem} {...formItemLayoutWithOutLabel}>
                                <Button type="dashed" onClick={this.add} style={{ width: '120%' }}>
                                    <Icon type="plus" /> 增加物料
                                </Button>
                            </FormItem>
                        </Col>
                        {/* <hr/> */}
                    </Row>
                    <div className={styles.formBox}>
                        {formItems}
                    </div>
                    <div style={{ width: '250px', height: 'auto', clear: 'both', padding: '20px 0', margin: '0px auto' }}>
                        <Button type="primary" onClick={this.handleSubmit} size="large" loading={this.state.loading}>
                            {this.state.loading ? '提交中...' : '确定'}
                        </Button>
                        <Button
                            type="default"
                            style={{ marginLeft: '50px' }}
                            size="large"
                            onClick={this.onCancel}
                        >
                            取消
                        </Button>

                        <ListModelDetail getTableData={this.getListModelDetailData} ref='listModelDetail' />
                    </div>
                </div>
            </Form>
        );
    }
}
let MyForm = Form.create()(SelfForm);


export default class EditPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            visible: false,
            url: '',
        };

    }
    handleOk = () => {
        // let result = this.state.resData;
        this.setState({
            visible: false,
        });
        this.refreshHandle();
    };

    handleCancel = () => {
        this.setState({
            visible: false,

        });
    };

    refreshHandle = () => {
        console.log("刷新List列表");
        this.props.refreshHandle();
    };

    // 手工出库任务新增(外部调用)
    addHandle = () => {
        this.setState({
            visible: true,
            resData: '',
            url: '/product/intowarehouse/checkIn/batch/insert',
            formTitle: '成品积压库存登记任务新增'
        });
    };

    // 手工出库任务修改(外部调用)
    editHandle = (rowObj) => {
        //根据对象的Id 属性获取对象信息
        let handInNo = rowObj[0].data.handInNo;
        const options = {
            url: '/product/intowarehouse/prohandin/get/' + handInNo,
            type: 'get',
            condition: {},
        };
        console.log('editHandle----------------------editHandle');
        fetchData(this, options, (resData) => {
            console.log('editHandle---------fetchData-------------editHandle');
            this.setState({
                url: '/product/intowarehouse/prohandin/batch/update',
                resData: resData,
                formTitle: '车辆登记任务修改',
                visible: true
            });
        });
    };

    render() {
        return (
            <Modal
                style={{ top: '20px' }}
                visible={this.state.visible}
                title={this.state.formTitle ? this.state.formTitle : '填写表单'}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                width={'850px'}
                footer=''
                maskClosable={false}
                closable={false}
            >
                <MyForm
                    ref='myForm'
                    dbOutCode={this.state.dbOutCode}
                    url={this.state.url}
                    getData={this.state.resData}
                    onCancel={this.handleCancel}
                    refreshHandle={this.refreshHandle}
                />
            </Modal>
        );
    }
}
